package com.example.demo.producer;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.constant.KafkaConstant;
import com.example.demo.entity.Log;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.kafka.support.SendResult;
import org.springframework.util.concurrent.ListenableFutureCallback;

import java.util.concurrent.Future;

@Component
public class LogProducer {

    @Autowired
    private KafkaTemplate kafkaTemplate;

    private static final Logger logger = LoggerFactory.getLogger(LogProducer.class);

    public void produceLog(Log log){
        String obj2String = JSONObject.toJSONString(log);
        logger.info("准备发送消息位：{}",obj2String);

        ListenableFuture<SendResult<String,Log>> future = kafkaTemplate.send(KafkaConstant.TOPIC_TEST,log);


        //如果失败，自带了重发机制
        future.addCallback(new ListenableFutureCallback<SendResult<String, Log>>() {
            @Override
            public void onFailure(Throwable throwable) {
                logger.info(KafkaConstant.TOPIC_TEST + " - 生产者 发送消息失败：" + throwable.getMessage());
            }

            @Override
            public void onSuccess(SendResult<String, Log> objectObjectSendResult) {
                logger.info(KafkaConstant.TOPIC_TEST + " - 生产者 发送消息成功：" + objectObjectSendResult.toString());
            }
        });
    }
}
